var obj1 = new Object({
    MessageType: 1002,
    Data: {
        UserID: storage.get('UserID')
    },
    ClientType: 2
});

var heartCheck = {
    timeout: 30000,
    timeoutObj: null,
    serverTimeoutObj: null,
    reset: function() {
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        return this;
    },
    start: function(wsClient) {
        var self = this;
        this.timeoutObj = setTimeout(function() {
            //这里发送一个心跳，后端收到后，返回一个心跳消息，onmessage拿到返回的心跳就说明连接正常
            //obj.MessageType = 2;
            wsClient.send(JSON.stringify(obj1));
            self.serverTimeoutObj = setTimeout(function() {
                //如果超过一定时间还没重置，说明后端主动断开了
                wsClient.close();
                //如果onclose会执行reconnect，我们执行ws.close()就行了.
                //如果直接执行reconnect 会触发onclose导致重连两次
            }, self.timeout)
        }, this.timeout)
    }
}

var errorCount = 0;

export default class WebSocketClass {
    /**
     * @description: 初始化实例属性，保存参数
     * @param {String} url ws的接口
     * @param {Function} msgCallback 服务器信息的回调传数据给函数
     * @param {String} name 可选值 用于区分ws，用于debugger
     */
    constructor(url, msgCallback, name = 'default') {
            this.url = url;
            this.msgCallback = msgCallback;
            this.name = name;
            this.lockReconnect = false;
            this.ws = null; // websocket对象
            this.status = null; // websocket是否关闭
            this.num = 5;
            this.timeoutObj = null;
            this.serverTimeoutObj = null;
            this.timeoutObj = 30000
        }
        /**
         * @description: 初始化 连接websocket或重连webSocket时调用
         * @param {*} 可选值 要传的数据
         */
    connect() {
        // 新建 WebSocket 实例
        this.ws = new WebSocket(this.url);
        console.log(this.ws)
        this.initEventHandle()
    }

    initEventHandle() {
        this.ws.onopen = () => {
                console.log('open');
                let all = {
                        "MessageType": 1000,
                        "ClientType": 2,
                        "Data": {
                            "UserID": storage.get('UserID'),
                            "Authorization": storage.get('token'),
                        }
                    }
                    // 连接ws成功回调
                this.ws.send(JSON.stringify(all));
                if (this.ws.readyState == 1) {
                    this.ws.send(JSON.stringify({
                        "MessageType": 1200,
                        "ClientType": 42,
                        "Data": {
                            "SenderID": storage.get('UserID'),
                            "SessionKeyword": "",
                            "PageIndex": 1,
                            "PageSize": 1
                        }
                    }))
                }
                // heartCheck.reset().start(this.ws);
            }
            // 监听服务器端返回的信息
        this.ws.onmessage = e => {
                // 把数据传给回调函数，并执行回调
                let result = e.data
                this.msgCallback(result)
            }
            // ws关闭回调
        this.ws.onclose = (e) => {
                this.closeHandle(e); // 判断是否关闭
            }
            // ws出错回调
        this.ws.onerror = e => {
            this.closeHandle(e); // 判断是否关闭
        }
    }

    // 重连
    reconnect() {
            if (this.lockReconnect) {
                return;
            }
            if (errorCount >= 10) {
                return;
            }
            console.log('重连了');
            this.lockReconnect = true;
            setTimeout(() => {
                this.connect()
                this.lockReconnect = false;
                errorCount++;
            }, 1000);
        }
        // 发送信息给服务器
    sendHandle(data) {
        return this.ws.send(data);
    }
    closeHandle() {
            // 因为webSocket并不稳定，规定只能手动关闭(调closeMyself方法)，否则就重连
            // if (this.pingInterval !== undefined && this.pongInterval !== undefined) {
            // 清除定时器
            clearInterval(this.pongInterval);
            // }
            if (this.status !== 'close' && this.num > 0) {
                --this.num
                this.connect(); // 重连
            } else {
                this.closeMyself()
            }
        }
        // 手动关闭WebSocket
    closeMyself() {
        this.status = 'close';
        return this.ws.close();
    }
}